package com.example.weather;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.example.weather.model.Constants;
import com.example.weather.model.PlaceResponse;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

public class MainActivity extends AppCompatActivity {

    private final Gson gson = new Gson();
    private final PlaceAdapter adapter = new PlaceAdapter(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //实例化控件
        EditText inputKey = findViewById(R.id.input_city);
        RecyclerView recyclerView = findViewById(R.id.recyclerView);

        //监听用户的输入
        inputKey.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //网络请求用户所输入的地址信息
                OkGo.<String>get(Constants.SEARCH_PLACE)
                        .params("query", s.toString())
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {
                                //通过gson解析json数据
                                PlaceResponse placeResponse = gson.fromJson(response.body(), PlaceResponse.class);
                                //判断是否请求成功
                                if (placeResponse.getStatus().equals("ok")) {
                                    //拿到数据后刷新recyclerView数据
                                    adapter.setList(placeResponse.getPlaces());
                                } else {
                                    //没有请求成功则清空数据 并且提示
                                    adapter.clearData();
                                    Toast.makeText(MainActivity.this, "没有找到相关地区", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
            }

            @Override
            public void afterTextChanged(Editable s) { }
        });

        //给recyclerView添加适配器
        recyclerView.setAdapter(adapter);
    }
}